<?php

class ProjectsController extends BaseController
{
    public function getPath(Project $project = null)
    {
        $path = array();
        $projects = Project::getAll();
        if (@count($projects) > 1) {
            $path['Список проектів'] = '/projects/';
        }

        switch ($this->action) {
            case 'editAction':
                $path['Редагування проекту ' . $project->name] = '/projects/edit/' . $project->id;
                break;
            case 'viewAction':
                $path['Проект ' . $project->title] = '/projects/view/' . $project->name;
                break;
        }
        return $path;
    }

    public function defaultAction()
    {
        $projects = Project::getAll();

        if (@count($projects) == 1) {
            Url::redirect('/projects/view/' . $projects[0]->name);
        }
        
        $this->view->assign('nav', $this->getPath());

        $this->view->assign('projects',$projects);
        $this->view->display('projects.default.tpl');   
        //print 'default action of ProjectsController';
    }

    public function manageAction()
    {
        $projects = Project::getAll();
        $this->view->assign('projects',$projects);
        $this->view->display('projects/manage.tpl');
    }

    public function createAction()
    {
        if ($_POST) {
            try {
                $project = new Project();
                $project->name = $_POST['alias'];
                $project->title = $_POST['title'];
                $project->repository_type = $_POST['reptype'];
                $project->create();
                Url::redirect('/projects/manage');
            } catch (Exception $e) {
                $this->view->assign('error',$e->getMessage());
            }
        }
        $this->view->display('projects/create.tpl');
    }

    public function editAction()
    {
        $id = $this->route->getParam('id');
        $project = Project::getById(intval($id));
        if (!$project) {
            Url::redirect('/projects/');
        }
        $this->view->assign('nav', $this->getPath($project));

        $this->view->assign('project', $project);
        $this->view->display('projects.edit.tpl');
    }

    public function deleteAction()
    {
        $id = $this->route->getParam('id');
        $project = Project::getById(intval($id));
        if (!$project) {
            Url::redirect('/projects/');
        }
        $project->delete();
        Url::goBack();
    }    

    public function closeAction()
    {
        $id = $this->route->getParam('id');
        $project = Project::getById(intval($id));
        if (!$project) {
            Url::redirect('/projects/');
        }
        $project->state = 0;
        $project->save();
        Url::goBack();
    }

    public function viewAction()
    {
        $name = $this->getParam('name');
        $project = Project::getByParams(array('name' => $name));
        if (!$project) {
            Url::redirect('/projects/');
        }
        $this->view->assign('nav', self::getPath($project));
        
        /*$covInfo = CoverageLineStatus::getProjectCoverageInfo($project->id);        

        $data = array();
        $legend = array();
        $colors = array();
        $labels = array();
        
        $sum = 0;
        foreach ($covInfo as &$item) {
            $sum += $item->count;
            switch($item->status) {
                case 0:
                case 1:
                    $sum -= $item->count;
                break;                
            }
        }
        foreach($covInfo as &$item) {            
            switch($item->status) {
                case 2:                    
                    $legend []= 'Uncovered'; 
                    $colors [] = 'FF4C4C';                    
                    $data []= $item->count;
                    $labels []= round(($item->count / $sum) * 100,2) . '%';
                break;                 
                case 3:
                    $legend []= 'Covered';   
                    $colors [] = '6CE26C';
                    $data []= $item->count;
                    $labels []= round(($item->count / $sum) * 100,2) . '%';
                break;                 
            }
        }*/
        
		/*print_r($data);
		print_r($labels);
		print_r($legend);
		print_r($colors);
		print_r($sum);*/
        //using('Framework.System.Google.Charts');
        //$str = GoogleCharts::getHtml('p', 350, 150, $data, $labels, $legend, $colors, 'Coverage');
        //$this->view->assign('img_tests', $str);

        $this->view->assign('tree', PhpdocPackage::getPackageTree());
        

        $this->view->assign('project', $project);
        $this->view->assign('projectSettings', $project->Settings);
        $this->view->display('projects.id.tpl');
    }
    
    public function searchAction()
    {
        //print_r($_GET);
        //$_GET['q'] = 'ormrecord';
        
        $query = trim($_GET['q']);
        if(empty($query)) {
            print 'empty query';
        }
        $stopSymbols = 'x27 x22 x60 \t \n \r \' , . / « » # ; : @ ~ [ ] { } = - + ) ( * & ^ % $ < > ? !';
        $query = str_replace($stopSymbols, null, $query);
        $words = explode(' ',$query);
        foreach($words as &$word) {
            if(mb_strlen($word) <= 2) {
                unset($word);
            }
        }
        
        $found = Project::search($words);        
        $this->view->assign('found', $found);
        $this->view->display('projects.search.tpl');
    }
    
    public function saveSettingsAction()
	{
        $name = $this->getParam('name');
        print $name;
        $project = Project::getByParams(array('name' => $name));        
        if (!$project) {
            //Url::goBack();
            print ' 404';
        }
        $settings = $project->Settings;
        $settings->tests_path = $_POST['tests_path'];
        $settings->low_cover_level = intval($_POST['low_cover_level']);
        $settings->middle_cover_level = intval($_POST['middle_cover_level']);
        $settings->high_cover_level = intval($_POST['high_cover_level']);
        $settings->save();
        
        Url::goBack();
    }    
    
	public static function generateContent(Project $project, File $file)
	{
		$content = $file->getFileContent();
		$path = DOCS_DIR . PATH_SEP . $file->getRelativePath($project->Folder) . '.xml';
		$info = Pfile::readDocumentorFile($path);
		$info = explode("\n", $info);
		return $info;
	}

	public function fileAction()
	{
		$id = $this->route->getParam('id');
		$file = Pfile::getById(intval($id));
		if (!$file) {
			Url::redirect('/');
		}

		$name = 'bazalt';//$this->route->getParam('id');
		$project = Project::getByParams(array('name' => $name));

		$this->view->assign('nav', $this->getPath());
		
		$content = self::generateContent($project, $file);
		
		//$this->view->assign('nav', $this->getPath($project));

		$this->view->assign('content', $content);
		$this->view->assign('file', $file);
		$this->view->assign('project', $project);
		$this->view->display('file.id.tpl');
	}

	private function savePath($path, $mask, Project $project, Pfolder $folder = null)
	{
		$arr = array(
					'parent_id' => (is_null($folder) ? null : $folder->id),
					'name' => basename($path),
					'path' => $path,
					'project_id' => $project->id);
		$nfolder = Pfolder::saveIfNotExists($arr);
		$this->saveFiles($path, $mask, $nfolder);

		foreach (glob($path . PATH_SEP . '*', GLOB_ONLYDIR) as $dir) {
			$this->savePath($dir, $mask, $project, $nfolder);
		}
		unset($nfolder);
		$nfolder = null;
	}

	private function saveFiles($path, $mask, Pfolder $folder)
	{
		echo $path . PATH_SEP . $mask;
		foreach (glob($path . PATH_SEP . $mask, GLOB_BRACE) as $filename) {
            $file = Pfile::saveIfNotExists(array('name' => basename($filename), 'folder_id' => $folder->id));

			continue;
			$handle = @fopen($filename, 'r');
			if ($handle) {
				$i = 0;
				while (!feof($handle)) {
					$line = fgets($handle, 4096);
                    $str = Pstring::saveIfNotExists(array('number' => $i++,'body' => rtrim($line), 'fileId' => $file->id));
					unset($str);
					$str = null;
				}
				fclose($handle);
			}
			unset($file);
			$file = null;
		}
	}

    public function scanAction()
	{
		set_time_limit(0);
		$name = $this->route->getParam('id');
		$project = Project::getByParams(array('name' => $name));
		if (!$project) {
			Url::redirect('/projects/');
		}

		/*using('Site.Code.Coverage');

		echo '<pre>';
		$dir = $project->getCoverageDir();
		$files = CoverageUtils::parseCoverageFiles($dir);
		foreach ($files as $k => $info) {
			$file = Pfile::getFile($k);
			CoverageFile::saveInfo($file, $info);
		}
	exit;*/

        
        using('Framework.System.IO');
        $path = FRAMEWORK_DIR;//dirname(__FILE__).'/tmp';
        //print $path.'<br/>';
        
        $allowExts = array('php', 'inc');
		$exts = '{' . implode(',', $allowExts) . '}';

		$pattern = $path . PATH_SEP . '*' . $exts;

		$this->savePath($path, '*.' . $exts, $project);

		exit;
		
		
        $di = new DirectoryInfo($path);
        
        $files = $di->getFiles('*.*',true);
        foreach($files as $file) {
            //$file->getFilename
            $p = str_replace($path,'',$file->getPath());
            $p = str_replace('\\','/',$p);
            $p = explode('/',$p);
            $folder = end($p);
            unset($p[count($p)-1]);
            $pth = implode('/',$p);
            if(empty($pth)) {
                $pth = '/';
            }
            
            $pfolder = Pfolder::saveIfNotExists(array('name'=>$folder,'path'=>$pth,'project_id'=>$project->id));
            $pfile = Pfile::saveIfNotExists(array('name'=> $file->getFilename(),'folder_id'=>$pfolder->id));
            
            $ext = strtolower( end(explode('.', $file->getFilename())) );
            if(in_array($ext,$allowExts)) {
                $content = '';
                try {
                    $content = file_get_contents($file->getPathname());
                } catch(Exception $e) {
                    print $e->getMessage();
                }
                $content = trim($content);
                $content = str_replace( "\n\r", "\n", $content );
                $content = str_replace( "\n\n", "\n", $content );
                $content = str_replace( "\r", "\n", $content );
                
                /*$content = explode("\n", $content);
                $i=1;
                foreach( $content as $str ) {
                    $str = rtrim($str);
                    if(empty($str)) {
                        continue;
                    }
                    $pstring = Pstring::save(array('number'=> $i,'body'=>$str,'fileId'=>$pfile->id));
					unset($pstring);
                    $i++;
                }*/
                
            }
			unset($pfile);
			unset($pfolder);
        }        
		
        print 'Done';
	}
}